package sktit.practice.jpaint.draw;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

import sktit.practice.jpaint.canvas.Canvas;
import sktit.practice.jpaint.canvas.PolygonCanvas;
import sktit.practice.jpaint.shape.Polygon;

public class PolygonDraw extends AbstractDraw {
	
	public PolygonDraw(Shell aShell, Display aDisplay, Color aColor, int aWidth,
			int aStyle)
	{
		super(aShell, aDisplay, aColor, aWidth, aStyle);
		
		mouseMoveListener = new MouseMoveListener(){

			@Override
			public void mouseMove(MouseEvent arg0) {
				if(isDrawing)
				{
					
					GC gc = createGC();
					Point previous = vertex.get(vertex.size() - 1);
					gc.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
					gc.drawLine(previous.x, previous.y, temp.x, temp.y);
					gc.setForeground(getColorBorder());
					
					if(Math.sqrt((arg0.x - begin.x)*(arg0.x - begin.x) + (arg0.y - begin.y)*(arg0.y - begin.y)) < 10)
					{
						gc.drawLine(previous.x, previous.y, begin.x, begin.y);
					} else
					{
						gc.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
						gc.drawLine(previous.x, previous.y, begin.x, begin.y);
						gc.setForeground(getColorBorder());
						gc.drawLine(previous.x, previous.y, arg0.x, arg0.y);
					}
					
					for(int i = 0; i < vertex.size() - 1; i++)
					{
						gc.drawLine(vertex.get(i).x, vertex.get(i).y, vertex.get(i+1).x, vertex.get(i+1).y);
					}
					
					
					
					gc.dispose();
					canvasManager.draw();
					temp.x = arg0.x;
					temp.y = arg0.y;
				}
				
			}
			
		};
		
		mouseListener = new MouseListener() {

			@Override
			public void mouseDoubleClick(MouseEvent arg0) {
				
			}

			@Override
			public void mouseDown(MouseEvent arg0) {
				if (!isDrawing) 
				{
					begin = new Point(arg0.x, arg0.y);
					temp = new Point(arg0.x, arg0.y);
					vertex.add(begin);
					isDrawing = true;
				}
			}

			@Override
			public void mouseUp(MouseEvent arg0) {
				Point p = new Point(arg0.x, arg0.y);
				if(Math.sqrt((p.x - begin.x)*(p.x - begin.x) + (p.y - begin.y)*(p.y - begin.y)) < 10)
				{
					isDrawing = false;
					Canvas polygonCanvas = new PolygonCanvas(createGC(), new Polygon(vertex));
					canvasManager.add(polygonCanvas);
					vertex.clear();
					return;
				} else
				{
					vertex.add(p);
				}
			}
			
		};
		
		shell.addMouseListener(mouseListener);
		shell.addMouseMoveListener(mouseMoveListener);
	}
	
	

}
